"""
Author        yongfa
Date          2021-11-19 16:00:02
LastEditTime  2022-10-14 15:14:23
LastEditors   yongfa
Description   AES 对称加密
"""


from flask import current_app
from Crypto.Cipher import AES
import base64


class Prpcrypt(object):
    """AES 对称加密"""

    # def __new__(cls):
    #     if not hasattr(cls, 'instance'):
    #         cls.instance = super().__new__(cls)
    #     return cls.instance

    def __init__(self, key: str = None):
        self.key = key if key else current_app.config.get('ENCRYPT_KEY')
        self.vi = self.key[0:AES.block_size]
        self.mode = AES.MODE_CBC

    # cryptographic functions
    def encrypt(self, text: str) -> str:
        """[加密]

        Args:
            text (str): [需要加密的字符串]

        Returns:
            str: [加密后的字符串]
        """

        text = text.encode('utf-8')
        cryptor = AES.new(self.key.encode('utf-8'), self.mode, self.vi.encode('utf-8'))
        length = 16
        count = len(text)
        add = length - (count % length)
        text = text + ('\0' * add).encode('utf-8')
        self.ciphertext = cryptor.encrypt(text)
        return base64.b64encode(self.ciphertext).decode('utf-8')

    def decrypt(self, text: str) -> str:
        """[解密]

        Args:
            text (str): [需要解密的字符串]

        Returns:
            str: [解密后的字符串]
        """
        cryptor = AES.new(self.key.encode('utf-8'), self.mode, self.vi.encode('utf-8'))
        plain_text = cryptor.decrypt(base64.b64decode(text)).decode('utf-8')
        return plain_text.rstrip('\0')

    @staticmethod
    def aes_decrypt_content(encrypted_content: str, encrypt_key: str) -> str:
        """解密支付宝 AES 加密的内容

        Args:
            encrypted_content (str): [加密的内容]
            encrypt_key (str): [加密的 key]

        Returns:
            str: [解密后的内容]
        """

        encrypted_content = base64.b64decode(encrypted_content)
        iv = encrypt_key[0:AES.block_size]

        def unpad(s):
            return s[:-ord(s[len(s) - 1:])]
        cryptor = AES.new(base64.b64decode(encrypt_key), AES.MODE_CBC, iv.encode('utf8'))  # 对iv做encode("utf8")处理
        content = unpad(cryptor.decrypt(encrypted_content)).decode('utf8')
        return content


if __name__ == '__main__':
    pc = Prpcrypt('CF3tEA1J2hRyIOw4')
    # pc = Prpcrypt('ao0oiou9S6na35Uvxa09SQ==')
    # e = pc.encrypt('123456')
    # d = pc.decrypt('NLhK7MOM+UO8wWTcYiO16Za2zQuouyJ+HZTG4EkOSrzgcMX1Xc9I0AEorlSalG5eozeVwYlaSHdoW0regVHwv2wsMvkXzOrJFZB/WQUOkOpYhjG8yQa9j2S+53z2xrnkS0SpRr0F4yGYw9a/yyaNaHsFAdulOCyoyc/maWBo2fQ+JRKCuPGvfRt+Eb7OPOcqAnLsSl+HxeBNXveclFwFdRA+t0M5JsRLxPPRx2ng3mx18eUzmGnWxrq+7jHi8dDMb7pJHGU9Y4B8G5NW0HVXwwz9ZvnI5pyQrVBfXAkq350g5GE4b56s4hzst9djroofNUFOQPlYIEAAAAlPadB9KvetFiLI4/muvUuwDNkgP6M=')
    # # print(e)
    # print(d)

    aes_key = 'ao0oiou9S6na35Uvxa09SQ=='
    # response = 'OC8mwW8nq56kul0YDBUCLZe+hxsjKCraVyCXXOlcpc6WLm+Q7RhXxqTeqr7zLt4t8aTtozMtnd4MKDyrNg2Wjg=='
    response = 'g98hA0Dsf9jjJb7lt2wDvoA9ms2jFR6h0Z/f3D7c1iT84mLE5XH/UwoPqCeja4eC'
    charset = 'utf-8'

    # print(pc.aes_decrypt_content(response, aes_key))
    # print(pc.aes_decrypt_content(response, 'CF3tEA1J2hRyIOw4'))
